package org.JWCB.friend.manager;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.JWCB.common.core.constants.CacheConstants;
import org.JWCB.common.core.constants.UserConstants;
import org.JWCB.common.core.utils.ThreadLocalUtil;
import org.JWCB.common.redis.service.RedisService;
import org.JWCB.friend.domain.user.entity.User;
import org.JWCB.friend.domain.user.vo.UserDetailVo;
import org.JWCB.friend.mapper.user.UserMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Slf4j
@RefreshScope
@Component
public class UserCacheManager {

    @Autowired
    private RedisService redisService;

    @Autowired
    private UserMapper userMapper;


    @Value("${user.cache.exp}")
    private long userExp;
    public UserDetailVo getUserInfo(Long userId) {
        String userKey = getUserKey(userId);
        // 从redis尝试获取
        UserDetailVo userDetailVo = redisService.getCacheObject(userKey,UserDetailVo.class);
        if(userDetailVo != null) {
            // 延长缓存过期时间
            redisService.expire(userKey,userExp);
            return userDetailVo;
        }
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>()
                .select(User::getUserId,
                        (User::getNickName),
                        (User::getPhone),
                        (User::getHeadImage),
                        (User::getSex),
                        (User::getEmail),
                        (User::getWechat),
                        (User::getSchool),
                        (User::getMajor),
                        (User::getIntroduce),
                        (User::getStatus))
                .eq(User::getUserId, userId));
        if(user == null){
            log.info("获取用户详情时userInfo为空");
            return null;
        }
        refreshUserCache(user);
        UserDetailVo retUserDetail = new UserDetailVo();
        BeanUtil.copyProperties(user,retUserDetail);
        return retUserDetail;
    }


    /**
     * 刷新redis缓存用户信息
     */
    public void refreshUserCache(User user) {
        String userKey = getUserKey(user.getUserId());
        redisService.setCacheObject(userKey,user,userExp, TimeUnit.MINUTES);
    }

    /**
     * 得到userInfo缓存key
     */
    private String getUserKey(long userId) {
        return CacheConstants.USER_INFO_KEY + userId;
    }


}
